package org.eirudy.shareimage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.eirudy.shareimage.constant.UserConstant;
import org.eirudy.shareimage.exception.BusinessException;
import org.eirudy.shareimage.exception.ErrorCode;
import org.eirudy.shareimage.exception.ThrowUtils;
import org.eirudy.shareimage.manager.auth.SpaceUserAuthManager;
import org.eirudy.shareimage.manager.sharding.DynamicShardingManager;
import org.eirudy.shareimage.mapper.SpaceUserMapper;
import org.eirudy.shareimage.model.dto.space.SpaceAddRequest;
import org.eirudy.shareimage.model.dto.space.SpaceQueryRequest;
import org.eirudy.shareimage.model.entity.Picture;
import org.eirudy.shareimage.model.entity.Space;
import org.eirudy.shareimage.model.entity.SpaceUser;
import org.eirudy.shareimage.model.entity.User;
import org.eirudy.shareimage.model.enums.SpaceLevelEnum;
import org.eirudy.shareimage.model.enums.SpaceRoleEnum;
import org.eirudy.shareimage.model.enums.SpaceTypeEnum;
import org.eirudy.shareimage.model.enums.UserRoleEnum;
import org.eirudy.shareimage.model.vo.PictureVO;
import org.eirudy.shareimage.model.vo.SpaceVO;
import org.eirudy.shareimage.model.vo.UserVO;
import org.eirudy.shareimage.service.SpaceService;
import org.eirudy.shareimage.mapper.SpaceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author Eirudy
* @description 针对表【space(空间)】的数据库操作Service实现
* @createDate 2025-05-27 15:36:43
*/
@Service
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space>
    implements SpaceService{


    @Resource
    private UserServiceImpl userServiceImpl;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private SpaceUserServiceImpl spaceUserServiceImpl;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

//    @Resource
//    @Lazy
//    private DynamicShardingManager dynamicShardingManager;

    @Override
    public long addSpace(SpaceAddRequest spaceAddRequest, User loginUser) {
        //1.填充参数
        Space space = new Space();
        // 转换实体类
        BeanUtil.copyProperties(spaceAddRequest, space);
        if(StrUtil.isBlank(space.getSpaceName())){
            space.setSpaceName("默认空间");
        }
        if(space.getSpaceLevel() == null){
            space.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        if (space.getSpaceType() == null) {
            space.setSpaceType(SpaceTypeEnum.PRIVATE.getValue());
        }


        //填充容量和大小
        this.fillSpaceBySpaceLevel(space);
        //2.校验参数
        this.validSpace(space,true);
        //3.校验权限，普通用户只能创建一个普通级别空间
        Long userId = loginUser.getId();
        space.setUserId(userId);
        if(SpaceLevelEnum.COMMON.getValue()!= space.getSpaceLevel() && !userServiceImpl.isAdmin(loginUser)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"权限错误，无指定级别的空间");
        }
        //4. 控制同一用户只能拥有一个私有空间
        String lock = String.valueOf(userId).intern(); // String.intern 每个字符串常量只有一个对象，保证锁只有一把
        synchronized (lock) {
            Long newSpaceId = transactionTemplate.execute(status ->
            {
            // 判断已有空间
                boolean exists = this.lambdaQuery()
                        .eq(Space::getUserId, userId)
                        .eq(Space::getSpaceType, space.getSpaceType())
                    .exists();

            //如果已有空间
                ThrowUtils.throwIf(exists, ErrorCode.OPERATION_ERROR, "每类空间只能创建一个");

            // 创建
            boolean result = this.save(space);
            ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR,"保存空间失败");

                // 如果是创建团队空间，将创建者自动添加到spaceUser
                if (SpaceTypeEnum.TEAM.getValue() == space.getSpaceType()) {
                    SpaceUser spaceUser = new SpaceUser();
                    spaceUser.setSpaceId(space.getId());
                    spaceUser.setUserId(userId);
                    spaceUser.setSpaceRole(SpaceRoleEnum.ADMIN.getValue());
                    spaceUser.setCreateTime(new Date());
                    spaceUser.setUpdateTime(new Date());
                    boolean resultAdd = spaceUserServiceImpl.save(spaceUser);
                    ThrowUtils.throwIf(!resultAdd,ErrorCode.OPERATION_ERROR,"创建团队成员记录");

                }
                //(仅对团队空间生效)
                //dynamicShardingManager.createSpacePicitureTable(space);
            return space.getId();
            });
            return newSpaceId;
        }

    }

    @Override
    public void validSpace(Space space, boolean add) {
        ThrowUtils.throwIf(space==null,ErrorCode.PARAMS_ERROR);

        // 从对象中取值
        Long id = space.getId();
        String spaceName = space.getSpaceName();
        Integer spaceLevel = space.getSpaceLevel();
        Integer spaceType = space.getSpaceType();
        SpaceLevelEnum levelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);
        SpaceTypeEnum spaceTypeEnum = SpaceTypeEnum.getEnumByValue(space.getSpaceType());
        // 创建时校验
        if(add){
            ThrowUtils.throwIf(StrUtil.isBlank(spaceName),ErrorCode.PARAMS_ERROR,"空间名称不能为空");
            ThrowUtils.throwIf(spaceLevel == null,ErrorCode.PARAMS_ERROR,"空间级别不能为空");
            ThrowUtils.throwIf(spaceType == null, ErrorCode.PARAMS_ERROR, "空间类型不能为空");

        }

        // 修改时校验
        if(StrUtil.isNotBlank(spaceName)){
            ThrowUtils.throwIf(spaceName.length() > 20,ErrorCode.PARAMS_ERROR,"空间名称 过长");
        }


        if(spaceLevel != null && levelEnum == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"空间级别错误");
        }

        if (spaceType != null && spaceTypeEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间类别错误");
        }


    }

    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        if (spaceQueryRequest == null) {
            throw  new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数为空");
        }

        QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
        Long id = spaceQueryRequest.getId();
        String spaceName = spaceQueryRequest.getSpaceName();
        Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
        Integer spaceType = spaceQueryRequest.getSpaceType();
        Long userId = spaceQueryRequest.getUserId();
        String sortField = spaceQueryRequest.getSortField();
        String sortOrder = spaceQueryRequest.getSortOrder();

        //空间信息
        queryWrapper.eq(ObjectUtil.isNotEmpty(id),"id", id);
        queryWrapper.like(StrUtil.isNotBlank(spaceName),"spaceName", spaceName);
        queryWrapper.eq(ObjectUtil.isNotEmpty(spaceLevel),"spaceLevel", spaceLevel);
        queryWrapper.eq(ObjectUtil.isNotEmpty(spaceType), "spaceType", spaceType);
        queryWrapper.eq(ObjectUtil.isNotEmpty(userId),"userId", userId);

        queryWrapper.orderBy(StrUtil.isNotBlank(sortField),sortOrder.equals("ascend"),sortField);
        return queryWrapper;
    }

    @Override
    public SpaceVO getSpaceVO(Space space, HttpServletRequest request) {
        SpaceVO spaceVO = SpaceVO.objToVo(space);

        Long userId = spaceVO.getUserId();
        if (userId != null) {
            User user = userServiceImpl.getById(userId);
            UserVO userVO = userServiceImpl.getUserVO(user);
            spaceVO.setUser(userVO);
            User loginUser = userServiceImpl.getLoginUser(request);
            spaceVO.setPermissionList(spaceUserAuthManager.getPermissionList(space,loginUser));
        }

        return spaceVO;
    }

    @Override
    public Page<SpaceVO> getSpaceVOPage(Page<Space> spacePage, HttpServletRequest request) {

        List<Space> spaceList = spacePage.getRecords();
        Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
        if (CollUtil.isEmpty(spaceList)) {
            return spaceVOPage;
        }
        // 对象列表 => 封装对象列表
        List<SpaceVO> spaceVOList = spaceList.stream().map(SpaceVO::objToVo).collect(Collectors.toList());
        // 1. 关联查询用户信息
        Set<Long> userIdSet = spaceList.stream().map(Space::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userServiceImpl.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        spaceVOList.forEach(spaceVO -> {
            Long userId = spaceVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            spaceVO.setUser(userServiceImpl.getUserVO(user));
        });
        spaceVOPage.setRecords(spaceVOList);
        return spaceVOPage;
    }

    @Override
    public void fillSpaceBySpaceLevel(Space space) {
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
        if(spaceLevelEnum != null){
            long maxCount = spaceLevelEnum.getMaxCount();
            long maxSize = spaceLevelEnum.getMaxSize();

            if(space.getMaxSize() == null){
                space.setMaxSize(maxSize);
            }

            if(space.getMaxCount() == null){
                space.setMaxCount(maxCount);
            }

        }

    }

    @Override
    public void checkSpaceAuth(Space space, User loginUser) {
        if (!loginUser.getUserRole().equals(UserConstant.ADMIN_ROLE) || !Objects.equals(space.getUserId(), loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限操作该空间");
        }
    }
}




